export default class AreaTool {
	constructor(viewer) {
		this.viewer = viewer;
		this.status = false;
		this.result = 0;
		this._init();
		this.pointGroups = [];
	}
	_init() {}
	start() {
		this.unit = this.viewer.getUnit();
		// 是否开启了
		this.status = true;
		if (this.viewer.measureTool) {
			this.viewer.measureTool.switchOff();
		}
		let drawableConfig = new Glodon.Bimface.Plugins.Drawable.DrawableContainerConfig();
		drawableConfig.viewer = this.viewer;
		//容器
		this.viewer.drawableContainer = new Glodon.Bimface.Plugins.Drawable.DrawableContainer(
			drawableConfig
		);

		this.viewer.addEventListener(
			Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked,
			this.areaLocation
		);
	}
	stop() {
		if (this.status) {
			this.viewer.measureTool.exit();
			this.status = false;
			for (let index = 0; index < this.pointGroups.length; index++) {
				this.viewer.drawableContainer.removeItemById(`area${index}`);
			}
			this.viewer.removeEventListener(
				Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked,
				this.areaLocation
			);
		}
	}
	areaLocation = (data) => {
		if (!data || data.eventType !== 'Click' || !data.worldPosition) return;

		// /引线标签的配置类
		let config = new Glodon.Bimface.Plugins.Drawable.CustomItemConfig();

		let rectangle = document.createElement('div');
		rectangle.style.width = '10px';
		rectangle.style.height = '10px';
		rectangle.style.borderRadius = '10px';
		rectangle.style.border = 'solid';
		rectangle.style.borderWidth = '3px';
		rectangle.style.borderColor = '#fff';
		rectangle.style.background = 'rgb(241 59 12)';
		config.content = rectangle;
		config.worldPosition = data.worldPosition;
		config.viewer = this.viewer;
		config.id = `area${this.pointGroups.length}`;
		if (data.worldPosition) {
			this.pointGroups.push(data);
		}

		let label = new Glodon.Bimface.Plugins.Drawable.CustomItem(config);
		this.viewer.drawableContainer.addItem(label);
	};

	calculateArea = () => {
		// let result;
		if (this.pointGroups.length > 2) {
			let i, j;
			let area = 0;
			for (i = 0; i < this.pointGroups.length; i++) {
				j = (i + 1) % this.pointGroups.length;
				area += this.pointGroups[i].worldPosition.x * this.pointGroups[j].worldPosition.y;
				area -= this.pointGroups[i].worldPosition.y * this.pointGroups[j].worldPosition.x;
			}
			area /= 2;
			if (this.unit === 'Millimeter') {
				this.result = Math.abs(area) / 1000000;
			} else {
				this.result = Math.abs(area);
			}
			for (let index = 0; index < this.pointGroups.length; index++) {
				this.viewer.drawableContainer.removeItemById(`area${index}`);
			}
			this.pointGroups = [];
		} else {
			this.result = 0;
		}
	};
	getArea() {
		this.calculateArea();
		return this.result;
	}
}
AreaTool.toolId = 'AreaTool';
